package system.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import system.common.Arguments;
import system.common.Constants;
import system.dao.DB1_WebkeeperDao;
import system.dao.DB1_WebkeeperMigrateDao;
import system.model.DB1_WebkeeperDto;
import collector.core.CollectConstants;
import collector.core.TaskConstVO;
import collector.core.util.DateUtil;
import collector.core.util.FileUtil;
import collector.task.JobStateVO;

/**
 * <pre>
 * Class : system.service.DB1_WebkeeperService / DB1_WebkeeperService.java
 * 	Define Class Object : 
 * <br>
 * </pre>
 * @author hwanLee / apexcns,Inc.
 * @version 1.2
 * @see javadoc
 * @since 2012. 9. 10.
 */
//@Service
public class DB1_WebkeeperService {
	@Autowired
	private DB1_WebkeeperDao db1_WebkeeperDao;
	
	@Autowired
	private DB1_WebkeeperMigrateDao db1_WebkeeperMigrateDao;

	private static Logger _log = LoggerFactory.getLogger(DB1_WebkeeperService.class);
	private static final String _LogPrefixStr = CollectConstants.LOGGER_MODULE_NAME_SMC + CollectConstants.LOGGER_MODULE_NAME_AFTFIX;//"test Log> ";

	public JobStateVO runWebkeeper(Arguments arguments, JobStateVO pjsVo, TaskConstVO tcVo) throws IOException, ParseException {
	    JobStateVO jsVo = pjsVo;
	    jsVo.setJobState(CollectConstants.CODE_JOB_STATE_DOING);
	    ExportService.OutputStateLog(jsVo);
	    ExportService.getNextSchedule(jsVo, tcVo, arguments);
	    
	    String fileNameSuffix = arguments.getParameter1() + "_" + arguments.getFileName1() + "_" + arguments.getFileName2();
		String historyFileName = tcVo.getTaskPathHistory() + tcVo.getTaskName() + "_" + DateUtil.dateToYmd(pjsVo.getScheduleTime(),"yyyyMMddHHmmss") + "_" + fileNameSuffix;
		String currentFileName = tcVo.getTaskPathCurrent() + tcVo.getTaskName();
		
		String dbName = null;
		String tableName1 = null;
		String tableName2 = null;
		if (tcVo.getTaskName().equals("WEBKEEPER_01")) {
			dbName = "WK_LOG_" + arguments.getDBName();
			tableName1 = "TB_LOG_HTTP_emd27w0_" + arguments.getDBName();
			tableName2 = "TB_LOG_USETIME_emd27w0_" + arguments.getDBName();
		} else {
			dbName = "WK_LOG_" + arguments.getDBName();
			tableName1 = "TB_LOG_HTTP_emd27w0_" + arguments.getDBName();
			tableName2 = "TB_LOG_USETIME_emd27w0_" + arguments.getDBName();
		}
		arguments.setDBFullName(dbName);
		
		// check for directory
		FileUtil.directoryCheck(tcVo.getTaskPathHistory());
		FileUtil.directoryCheck(tcVo.getTaskPathCurrent());
		
		// delete to current file
		FileUtil.deleteFile(tcVo.getTaskName(), tcVo.getTaskPathCurrent());
		
		String stepNumber;
		int timeNumber;
		String tableTimeName;
		long start;
		long end;
		long recordsCount = 0;
		float rsTime;
		float fileMakeTime;
		
		File file = null;
		BufferedWriter bufferedWriter = null;
		
		float totalRsTime = 0;
		float totalFileMakeTime = 0;
		float totalFileCopyTime = 0;
		long totalRecordsCount = 0;
		int totalFilesCount = 0;
		
		List<DB1_WebkeeperDto> webkeeper_list;
		
		String startTime = arguments.getParameter2();
		String endTime = arguments.getParameter3();

		jsVo.setJobCondStartTime(startTime);
		jsVo.setJobCondEndTime(endTime);
		
		if (arguments.getParameter1().equals("DAY")) {
			String tempStartTime = startTime;
			String tempEndTime;
			int roofCount = 48 * jsVo.getJobDurationValue();
			
			Date d;
			DateUtil.setDefaultDateFormat("yyyyMMddHHmm");
			for (int i = 1; i <= roofCount; i++) {
				d = Constants.simDf_Min.parse(startTime);
				tempEndTime = DateUtil.dateAddFormat(Calendar.MINUTE, (i * 30), d);
				arguments.setParameter2(tempStartTime, 1);
				if (i == roofCount) {
					arguments.setParameter3(endTime, 1);
				} else {
					arguments.setParameter3(tempEndTime, 1);
				}
				// rs start
				start = System.currentTimeMillis();

				timeNumber = Integer.parseInt(startTime.substring(11, 13));
				if (timeNumber % 2 != 0) {
					timeNumber = timeNumber - 1;
				}
				tableTimeName = "0" + timeNumber;
				arguments.setTableName1(tableName1 + "_" + tableTimeName.substring((tableTimeName.length() - 2), tableTimeName.length()));
				arguments.setTableName2(tableName2 + "_" + tableTimeName.substring((tableTimeName.length() - 2), tableTimeName.length()));
				
				if (tcVo.getTaskName().equals("WEBKEEPER_01")) {
					webkeeper_list = db1_WebkeeperDao.webkeeper_01_list(arguments);
				} else {
					webkeeper_list = db1_WebkeeperDao.webkeeper_02_list(arguments);
				}

				recordsCount = webkeeper_list.size();
				totalRecordsCount += recordsCount;

				end = System.currentTimeMillis();
				rsTime = (end - start) / 1000f;
				totalRsTime += rsTime;
				// rs end
				// file-make start
				start = System.currentTimeMillis();
				
				stepNumber = "000" + i;
				file = new File(historyFileName + "_" + stepNumber.substring((stepNumber.length() - 4), stepNumber.length()) + FileUtil.genFileNumber(0) + Constants.fileNameExtension);
				bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));

				totalFilesCount += ExportService.OutputList(webkeeper_list, bufferedWriter, historyFileName, "_" + stepNumber.substring((stepNumber.length() - 4), stepNumber.length()), 0, tcVo.getTaskName());
				
				end = System.currentTimeMillis();
				fileMakeTime = (end - start) / 1000f;
				totalFileMakeTime += fileMakeTime;
				// file-make end
				_log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
				_log.debug(_LogPrefixStr + "|" + " step-" + i + " :: record(" + webkeeper_list.size() + "), rs(" + rsTime + "s)");
				_log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
				
				d = Constants.simDf_Min.parse(tempEndTime);
				tempStartTime = DateUtil.dateAddFormat(Calendar.MINUTE, 1, d);
			}
			// file-copy start
			start = System.currentTimeMillis();
			
			FileUtil.copyBytes(tcVo.getTaskPathHistory(), tcVo.getTaskName() + "_" + DateUtil.dateToYmd(pjsVo.getScheduleTime(),"yyyyMMddHHmmss") + "_" + fileNameSuffix, currentFileName, Constants.fileNameExtension);

			end = System.currentTimeMillis();
			totalFileCopyTime = (end - start) / 1000f;
			// file-copy end
		} else {
			// rs start
			start = System.currentTimeMillis();
			
			timeNumber = Integer.parseInt(startTime.substring(11, 13));
			if (timeNumber % 2 != 0) {
				timeNumber = timeNumber - 1;
			}
			tableTimeName = "0" + timeNumber;
			arguments.setTableName1(tableName1 + "_" + tableTimeName.substring((tableTimeName.length() - 2), tableTimeName.length()));
			arguments.setTableName2(tableName2 + "_" + tableTimeName.substring((tableTimeName.length() - 2), tableTimeName.length()));
			
			if (tcVo.getTaskName().equals("WEBKEEPER_01")) {
				webkeeper_list = db1_WebkeeperDao.webkeeper_01_list(arguments);
			} else {
				webkeeper_list = db1_WebkeeperDao.webkeeper_02_list(arguments);
			}
			
			totalRecordsCount = webkeeper_list.size();

			end = System.currentTimeMillis();
			totalRsTime = (end - start) / 1000f;
			// rs end
			// file-make start
			start = System.currentTimeMillis();
			
			file = new File(historyFileName + "_0001" + FileUtil.genFileNumber(0) + Constants.fileNameExtension);
			bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));

			totalFilesCount = ExportService.OutputList(webkeeper_list, bufferedWriter, historyFileName, "_0001", 0, tcVo.getTaskName());
			
			end = System.currentTimeMillis();
			totalFileMakeTime = (end - start) / 1000f;
			// file-make end
			// file-copy start
			start = System.currentTimeMillis();
			
			FileUtil.copyBytes(tcVo.getTaskPathHistory(), tcVo.getTaskName() + "_" + DateUtil.dateToYmd(pjsVo.getScheduleTime(),"yyyyMMddHHmmss") + "_" + fileNameSuffix, currentFileName, Constants.fileNameExtension);

			end = System.currentTimeMillis();
			totalFileCopyTime = (end - start) / 1000f;
			// file-copy end
		}
		
		//jsVo.setJobAuto(jobAuto);
		jsVo.setTotalFileCount(totalFilesCount);
		jsVo.setTotalRecordCount(totalRecordsCount);
		jsVo.setRsTime(totalRsTime);
		jsVo.setFileMakeTime(totalFileMakeTime);
		jsVo.setFileCopyTime(totalFileCopyTime);
		
		jsVo.setSuccDoneResult(CollectConstants.CODE_JOB_RESULT_CODE_SUCC, "do Job Succ State...");
		
		// 작업 상태 객체 리턴
		return jsVo;
	}
	
	public JobStateVO runWebkeeperMigrate(Arguments arguments, JobStateVO pjsVo, TaskConstVO tcVo) throws IOException, ParseException {
	    JobStateVO jsVo = pjsVo;
	    jsVo.setJobState(CollectConstants.CODE_JOB_STATE_DOING);
	    ExportService.OutputStateLog(jsVo);
	    ExportService.getNextSchedule(jsVo, tcVo, arguments);
	    
	    String fileNameSuffix = arguments.getParameter1() + "_" + arguments.getFileName1() + "_" + arguments.getFileName2();
		String historyFileName = tcVo.getTaskPathHistory() + tcVo.getTaskName() + "_" + DateUtil.dateToYmd(pjsVo.getScheduleTime(),"yyyyMMddHHmmss") + "_" + fileNameSuffix;
		String currentFileName = tcVo.getTaskPathCurrent() + tcVo.getTaskName();
		
		String dbName = null;
		String tableName1 = null;
		String tableName2 = null;
		if (tcVo.getTaskName().equals("WEBKEEPER_MIGRATE_01")) {
			dbName = "WK_LOG_" + arguments.getDBName();
			tableName1 = "TB_LOG_HTTP_emd27w0_" + arguments.getDBName();
			tableName2 = "TB_LOG_USETIME_emd27w0_" + arguments.getDBName();
		} else {
			dbName = "WK_LOG_" + arguments.getDBName();
			tableName1 = "TB_LOG_HTTP_emd27w0_" + arguments.getDBName();
			tableName2 = "TB_LOG_USETIME_emd27w0_" + arguments.getDBName();
		}
		arguments.setDBFullName(dbName);
		
		// check for directory
		FileUtil.directoryCheck(tcVo.getTaskPathHistory());
		FileUtil.directoryCheck(tcVo.getTaskPathCurrent());
		
		// delete to current file
		FileUtil.deleteFile(tcVo.getTaskName(), tcVo.getTaskPathCurrent());
		
		String stepNumber;
		int timeNumber;
		String tableTimeName;
		long start;
		long end;
		long recordsCount = 0;
		float rsTime;
		float fileMakeTime;
		
		File file = null;
		BufferedWriter bufferedWriter = null;
		
		float totalRsTime = 0;
		float totalFileMakeTime = 0;
		float totalFileCopyTime = 0;
		long totalRecordsCount = 0;
		int totalFilesCount = 0;
		
		List<DB1_WebkeeperDto> webkeeper_migrate_list;
		
		String startTime = arguments.getParameter2();
		String endTime = arguments.getParameter3();

		jsVo.setJobCondStartTime(startTime);
		jsVo.setJobCondEndTime(endTime);
		
		if (arguments.getParameter1().equals("DAY")) {
			String tempStartTime = startTime;
			String tempEndTime;
			int roofCount = 48 * jsVo.getJobDurationValue();
			
			Date d;
			DateUtil.setDefaultDateFormat("yyyyMMddHHmm");
			for (int i = 1; i <= roofCount; i++) {
				d = Constants.simDf_Min.parse(startTime);
				tempEndTime = DateUtil.dateAddFormat(Calendar.MINUTE, (i * 30), d);
				arguments.setParameter2(tempStartTime, 1);
				if (i == roofCount) {
					arguments.setParameter3(endTime, 1);
				} else {
					arguments.setParameter3(tempEndTime, 1);
				}
				// rs start
				start = System.currentTimeMillis();

				timeNumber = Integer.parseInt(startTime.substring(11, 13));
				if (timeNumber % 2 != 0) {
					timeNumber = timeNumber - 1;
				}
				tableTimeName = "0" + timeNumber;
				arguments.setTableName1(tableName1 + "_" + tableTimeName.substring((tableTimeName.length() - 2), tableTimeName.length()));
				arguments.setTableName2(tableName2 + "_" + tableTimeName.substring((tableTimeName.length() - 2), tableTimeName.length()));
				
				if (tcVo.getTaskName().equals("WEBKEEPER_MIGRATE_01")) {
					webkeeper_migrate_list = db1_WebkeeperMigrateDao.webkeeper_migrate_01_list(arguments);
				} else {
					webkeeper_migrate_list = db1_WebkeeperMigrateDao.webkeeper_migrate_02_list(arguments);
				}

				recordsCount = webkeeper_migrate_list.size();
				totalRecordsCount += recordsCount;

				end = System.currentTimeMillis();
				rsTime = (end - start) / 1000f;
				totalRsTime += rsTime;
				// rs end
				// file-make start
				start = System.currentTimeMillis();
				
				stepNumber = "000" + i;
				file = new File(historyFileName + "_" + stepNumber.substring((stepNumber.length() - 4), stepNumber.length()) + FileUtil.genFileNumber(0) + Constants.fileNameExtension);
				bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));

				totalFilesCount += ExportService.OutputList(webkeeper_migrate_list, bufferedWriter, historyFileName, "_" + stepNumber.substring((stepNumber.length() - 4), stepNumber.length()), 0, tcVo.getTaskName());
				
				end = System.currentTimeMillis();
				fileMakeTime = (end - start) / 1000f;
				totalFileMakeTime += fileMakeTime;
				// file-make end
				_log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
				_log.debug(_LogPrefixStr + "|" + " step-" + i + " :: record(" + webkeeper_migrate_list.size() + "), rs(" + rsTime + "s)");
				_log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
				
				d = Constants.simDf_Min.parse(tempEndTime);
				tempStartTime = DateUtil.dateAddFormat(Calendar.MINUTE, 1, d);
			}
			// file-copy start
			start = System.currentTimeMillis();
			
			FileUtil.copyBytes(tcVo.getTaskPathHistory(), tcVo.getTaskName() + "_" + DateUtil.dateToYmd(pjsVo.getScheduleTime(),"yyyyMMddHHmmss") + "_" + fileNameSuffix, currentFileName, Constants.fileNameExtension);

			end = System.currentTimeMillis();
			totalFileCopyTime = (end - start) / 1000f;
			// file-copy end
		} else {
			// rs start
			start = System.currentTimeMillis();
			
			timeNumber = Integer.parseInt(startTime.substring(11, 13));
			if (timeNumber % 2 != 0) {
				timeNumber = timeNumber - 1;
			}
			tableTimeName = "0" + timeNumber;
			arguments.setTableName1(tableName1 + "_" + tableTimeName.substring((tableTimeName.length() - 2), tableTimeName.length()));
			arguments.setTableName2(tableName2 + "_" + tableTimeName.substring((tableTimeName.length() - 2), tableTimeName.length()));
			
			if (tcVo.getTaskName().equals("WEBKEEPER_01")) {
				webkeeper_migrate_list = db1_WebkeeperMigrateDao.webkeeper_migrate_01_list(arguments);
			} else {
				webkeeper_migrate_list = db1_WebkeeperMigrateDao.webkeeper_migrate_02_list(arguments);
			}
			
			totalRecordsCount = webkeeper_migrate_list.size();

			end = System.currentTimeMillis();
			totalRsTime = (end - start) / 1000f;
			// rs end
			// file-make start
			start = System.currentTimeMillis();
			
			file = new File(historyFileName + "_0001" + FileUtil.genFileNumber(0) + Constants.fileNameExtension);
			bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));

			totalFilesCount += ExportService.OutputList(webkeeper_migrate_list, bufferedWriter, historyFileName, "_0001", 0, tcVo.getTaskName());
			
			end = System.currentTimeMillis();
			totalFileMakeTime = (end - start) / 1000f;
			// file-make end
			// file-copy start
			start = System.currentTimeMillis();
			
			FileUtil.copyBytes(tcVo.getTaskPathHistory(), tcVo.getTaskName() + "_" + DateUtil.dateToYmd(pjsVo.getScheduleTime(),"yyyyMMddHHmmss") + "_" + fileNameSuffix, currentFileName, Constants.fileNameExtension);

			end = System.currentTimeMillis();
			totalFileCopyTime = (end - start) / 1000f;
			// file-copy end
		}
		
		//jsVo.setJobAuto(jobAuto);
		jsVo.setTotalFileCount(totalFilesCount);
		jsVo.setTotalRecordCount(totalRecordsCount);
		jsVo.setRsTime(totalRsTime);
		jsVo.setFileMakeTime(totalFileMakeTime);
		jsVo.setFileCopyTime(totalFileCopyTime);
		
		jsVo.setSuccDoneResult(CollectConstants.CODE_JOB_RESULT_CODE_SUCC, "do Job Succ State...");
		
		// 작업 상태 객체 리턴
		return jsVo;
	}
}
